package FlyWeight;

import java.util.HashMap;

//享元模式
public class FlyWeightPattern {
    public static void main(String[] args) {
        FlyWeightFactory factory = new FlyWeightFactory();
        FlyWeight f01 = factory.getFlyWeight("a");
        FlyWeight f02 = factory.getFlyWeight("b");
        FlyWeight f03 = factory.getFlyWeight("c");
        FlyWeight f11 = factory.getFlyWeight("a");
        FlyWeight f12 = factory.getFlyWeight("b");
        FlyWeight f13 = factory.getFlyWeight("c");
        f01.operation(new UnsharedConcreteFlyWeight("第一次调用a"));
        f11.operation(new UnsharedConcreteFlyWeight("第二次调用a"));
        f02.operation(new UnsharedConcreteFlyWeight("第一次调用b"));
        f12.operation(new UnsharedConcreteFlyWeight("第二次调用b"));
        f03.operation(new UnsharedConcreteFlyWeight("第一次调用c"));
        f13.operation(new UnsharedConcreteFlyWeight("第二次调用c"));
    }
}
//非享元角色
class UnsharedConcreteFlyWeight{
    private String info;

    public UnsharedConcreteFlyWeight(String info) {
        this.info = info;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }
}
//抽象享元角色
interface FlyWeight{
    public void operation(UnsharedConcreteFlyWeight unsharedConcreteFlyWeight);
}
//具体享元角色
class ConcreteFlyWeight implements FlyWeight{
    private String key;

    public ConcreteFlyWeight(String key) {
        this.key = key;
        System.out.println("具体享元"+key);
    }
    @Override
    public void operation(UnsharedConcreteFlyWeight unsharedConcreteFlyWeight) {
        System.out.println("具体享元"+key+"被调用");
        System.out.println("非享元信息是："+unsharedConcreteFlyWeight.getInfo());
    }
}
//享元工厂角色
class FlyWeightFactory{
    private HashMap<String,FlyWeight> flyWeightHashMap = new HashMap<String, FlyWeight>();
    public FlyWeight getFlyWeight(String key){
        FlyWeight flyWeight = (FlyWeight)flyWeightHashMap.get(key);//获取value
        if (flyWeight!=null){
            //非空
            System.out.println("具体享元"+key+"已经存在");
        }else{
            flyWeight = new ConcreteFlyWeight(key);
            flyWeightHashMap.put(key,flyWeight);//存入
        }
        return flyWeight;
    }
}